package com.huweilong.tingshu.servlet.publish;

import com.huweilong.tingshu.repository.TrackRepo;
import com.huweilong.tingshu.util.Log;
import com.huweilong.tingshu.view_object.publish.PlayTrack;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 是阿秋啊
 * @date 2022/07/23 15:29
 **/
@WebServlet("/track")
public class TrackServlet extends HttpServlet {
    private final TrackRepo trackRepo = new TrackRepo();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tid = req.getParameter("tid");
        PlayTrack playTrack = trackRepo.selectTarckByTid(tid);
        // 此处响应不是文本,是二进制数据,不需要字符串
        resp.setContentType(playTrack.type);
        // 二进制响应,不用resp.getWriter() 用 resp.getOutputStream
        ServletOutputStream os = resp.getOutputStream();
        // 把数据从 content(InputStream)搬到os(OutputStream)
        // 利用一个桶byte[] 一点点搬
        byte[] buf = new byte[4096];
        while (true) {
            int n = playTrack.content.read(buf);
            if (n == -1) {
                break;
            }

            os.write(buf,0,n);
        }
        os.flush();
        playTrack.content.close();
        Log.println("歌曲已发送");
    }
}